<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="searchUser"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchUser"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = !dialogVisible">
            添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <!-- scope.row.mg_state -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDilog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                @click="setInfo(scope.row)"
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="resetForm('addFormRef')"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addFormRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <edit @getList="getUserList"></edit>
    <el-dialog
      title="提示"
      :visible.sync="setRulesDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <span>分配角色</span>
      <p>当前用户:{{ role.username }}</p>
      <p>当前角色:{{ role.role_name }}</p>
      <p>
        分配新角色:<el-select v-model="selectedRole" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRulesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import edit from '../plugins/editDialogVisible'
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState(['editDialogVisible'])
  },
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号码'))
    }
    return {
      setRulesDialogVisible: false,

      addFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            message: '邮箱格式不正确，请重新输入',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkMobile,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur'
          }
        ]
      },
      addForm: { username: '', password: '', email: '', mobile: '' },
      dialogVisible: false,
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      role: {},
      roleList: [],
      selectedRole: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    setRoleDialogClosed() {
      this.selectedRole = ''
    },
    async saveRoleInfo() {
      const { data } = await this.$http.put(`users/${this.role.id}/role`, {
        rid: this.selectedRole
      })
      if (data.meta.status !== 200) return this.$message.error('更新角色失败')

      this.$message.success('更新角色成功')
      this.getUserList()
      this.setRulesDialogVisible = false
    },
    async setInfo(role) {
      this.role = role
      const { data } = await this.$http.get('roles')
      if (data.meta.status !== 200) return this.$message.error('数据角色失败')
      this.roleList = data.data

      this.setRulesDialogVisible = !this.setRulesDialogVisible
    },
    removeUserById(id) {
      this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await this.$http.delete('users/' + id)

          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async showEditDilog(id) {
      const { data } = await this.$http.get('users/' + id)
      if (data.meta.status !== 200) return this.$message.error('数据获取失败')
      this.$store.commit('editFormAdd', data.data)
    },

    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写完整用户信息')
        }
        const { data } = await this.$http.post('users', this.addForm)
        if (data.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    searchUser() {
      this.getUserList()
    },
    async userChange(users) {
      const { data } = await this.$http.put(
        `users/${users.id}/state/${users.mg_state}`
      )
      if (data.meta.status !== 200) {
        this.$message.error('更改失败')
        users.mg_state = !users.mg_state
      }
      this.$message.success('更改成功')
    },
    async getUserList() {
      const { data } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (data.data.users.length === 0) {
        this.queryInfo.pagenum--
        const res = await this.$http.get('users', {
          params: this.queryInfo
        })
        if (res.data.meta.status !== 200) return this.$message.error('获取失败')
        this.userList = res.data.data.users
        this.total = res.data.data.total
      } else {
        if (data.meta.status !== 200) return this.$message.error('获取失败')
        this.userList = data.data.users
        this.total = data.data.total
      }
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    }
  },
  components: {
    edit: edit
  }
}
</script>
<style lang="less" scoped></style>
